﻿using System;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using Microsoft.SharePoint;
using Microsoft.SharePoint.Utilities;
using Microsoft.SharePoint.WebControls;
using System.Globalization;
using System.IO;
using System.Collections;
using Microsoft.SharePoint.Portal;
using Microsoft.SharePoint.Portal.WebControls;
using Microsoft.SharePoint.Taxonomy;
using System.Linq;
using System.Collections.Generic;

namespace LB.GlobalSuiteLinks.ControlTemplates.LB.GlobalSuiteLinks
{
    public partial class SuiteLinksDelegateCtrl : MySuiteLinksUserControl
    {
        protected void Page_Load(object sender, EventArgs e)
        {
        }

        protected override void Render(HtmlTextWriter writer)
        {
            //TODO
            //Create admin page is site setting to allow input of managed meta data id
            //Connect to term set

            string overideRendering = string.Empty;

            try
            {
                using (SPSite site = new SPSite(SPContext.Current.Site.Url))
                {
                    //Get the rootweb as we cannot store properties in the site collection.
                    SPWeb rootWeb = site.RootWeb;

                    //Check that a properties collection exists.
                    if (rootWeb.Properties != null && rootWeb.Properties.Count > 0)
                    {
                        //Check that the SuiteBarOveride property exists in the rootweb property collection. Skip if it doesnt exist
                        if (rootWeb.Properties.ContainsKey("SuiteBarOveride"))
                        {
                            //Set the value of the var holding the value for later use.
                            overideRendering = rootWeb.Properties["SuiteBarOveride"].ToString().ToLower();
                        }

                        //Check that the SuiteBarTermStoreId property exists in the rootweb property collection. Skip if it doesnt exist
                        if (rootWeb.Properties["SuiteBarTermStoreId"] !="1")
                        {
                            //Build additional strings from the value of the SuiteBarTermStoreId property value.
                            string property = rootWeb.Properties["SuiteBarTermStoreId"].ToString();
                            if (property.Length !=0)
                            {
                                var x = property.Length;
                                string setId = property.Split(Convert.ToChar(","))[0].ToString();
                                string groupId = property.Split(Convert.ToChar(","))[1].ToString();


                                //Define a new sorted dictionary to sort out custom links alphabetically.
                                SortedDictionary<string, string> dictionary = new SortedDictionary<string, string>();

                                //Connect to the taxonomy session.
                                TaxonomySession session = new TaxonomySession(SPContext.Current.Site);
                                TermStoreCollection termstores = session.TermStores;
                                TermStore defaultTermStore = termstores[0];

                                //Get the group, by id, of the group that holds the termset selected on the admin page.
                                Group group1 = (from groups in defaultTermStore.Groups
                                                where groups.Id == new Guid(groupId)
                                                select groups).FirstOrDefault();

                                if (group1 != null)
                                {
                                    //Get the termset selected in the admin page by id.
                                    TermSet termSet = (from termSets in group1.TermSets
                                                       where termSets.Id == new Guid(setId)
                                                       select termSets).FirstOrDefault();

                                    //Check the termset has terms.
                                    if (termSet != null)
                                    {
                                        //Render the opening UL tag.
                                        writer.RenderBeginTag(HtmlTextWriterTag.Style);
                                        writer.Write(".ms-core-suiteLinkList {display: inline-block;}");
                                        writer.RenderEndTag();
                                        writer.AddAttribute(HtmlTextWriterAttribute.Class, "ms-core-suiteLinkList");
                                        writer.RenderBeginTag(HtmlTextWriterTag.Ul);
                                        foreach (Term item in termSet.Terms)
                                        {
                                            //Check simple url exists and set value as hash if it does not.
                                            string url;
                                            try
                                            {
                                                url = item.LocalCustomProperties["_Sys_Nav_SimpleLinkUrl"].ToString();
                                            }
                                            catch { url = "#"; }

                                            //Check if the title overide has been used for the term.
                                            if (item.LocalCustomProperties.Count > 1)
                                            {
                                                //Add item to dictionary.
                                                dictionary.Add(item.LocalCustomProperties["_Sys_Nav_Title"].ToString(),
                                                    url);
                                            }
                                            else
                                            {
                                                //Add item to dictionary.
                                                dictionary.Add(item.Name, url);
                                            }
                                        }
                                        //Iterate the dictionary and render the suite link items.
                                        foreach (var item in dictionary)
                                        {
                                            RenderSuiteLink(writer, item.Value, item.Key, item.Key, false);
                                        }
                                        //Render the closing tag.
                                        writer.RenderEndTag();
                                    }
                                }
                            }
                        }
                    }
                }
            }
            catch {
                base.Render(writer);
            }
            try
            {
                if (overideRendering == "false" || overideRendering == string.Empty)
                {
                    base.Render(writer);
                }
            }
            catch
            {
                base.Render(writer);
            }         
        }
    }
}
